/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.ssau.view;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;

/**
 *
 * @author Дима
 */
public class ConnectionDialog extends JDialog {

    private JTextField hostField;
    private JTextField portField;
    private JButton okButton;
    private JButton cancelButton;

    private String host;
    private int port;

    private boolean ok = false;

    public ConnectionDialog(JFrame parent) {
        super(parent, "Connect to server", true);
        initComponents();
        layoutComponents();
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        pack();
    }

    private void initComponents() {
        hostField = new JTextField("localhost");
        portField = new JTextField("8189");
        okButton = new JButton("OK");
        cancelButton = new JButton("Cancel");

        okButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ok = true;
                try {
                    port = Integer.parseInt(portField.getText());
                    host = hostField.getText();
                    setVisible(false);
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(ConnectionDialog.this, "Wrong port value", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
    }

    private void layoutComponents() {
        JPanel mainPanel = new JPanel(new GridLayout(2,2));
        mainPanel.add(new JLabel("Host: ", JLabel.RIGHT));
        mainPanel.add(hostField);
        mainPanel.add(new JLabel("Port: ", JLabel.RIGHT));
        mainPanel.add(portField);
        add(mainPanel, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(okButton);
        buttonPanel.add(cancelButton);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    public boolean showDialog() {
        ok = false;
        setVisible(true);
        return ok;
    }

    public String getHost() {
        return host;
    }

    public int getPort() {
        return port;
    }

}
